package controller

import (
	"EnjoyWorking/model"
	"EnjoyWorking/utils"
	"EnjoyWorking/web/service"
	"github.com/kataras/golog"
	"github.com/kataras/iris/v12"
	"github.com/kataras/iris/v12/hero"
	"strings"
)

func NewInterfaceDetailController(app *iris.Application, party iris.Party) {
	var (
		adinUser = party.Party("/interface")
		controller      = InterfaceDetail{service: service.InterfaceDetail{}}
	)

	adinUser.Get("/getAll", hero.Handler(controller.GetAll)).Name = "接口列表"

	//创建权限表
	list := app.GetRoutes()
	for _, v := range list {
		if v.Method == "OPTIONS" {
			continue
		}
		if strings.Index(v.Path, "/api/") != -1 && v.Description != "" {
			if controller.service.Count(v.Path) == 0 {
				interfaceDetail := &model.InterfaceDetail{
					ID:          0,
					Name:        v.Name,
					Path:        v.Path,
					Method:      v.Method,
					Description: v.Description,
				}
				controller.service.Insert(interfaceDetail)
			}
		}
	}
}

type InterfaceDetail struct {
	service service.InterfaceDetail
}

func (controller *InterfaceDetail) GetAll(ctx iris.Context) {
	var (
		err    error
		code   utils.Code
		total  int64
		result []*model.InterfaceDetail
	)

	if total, result, err = controller.service.FindList(); err != nil {
		goto ERR
	}
	utils.PaginationTableData(ctx, total, result)
	return
ERR:
	golog.Errorf("失败。原因：%s，错误：%s", code.String(), err)
	utils.InternalServerError(ctx, code, err)
}